package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-01
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IoTDAClient aClient;


    /**
     * 查询设备信息列表
     *
     * @param device 设备信息
     * @return 设备信息
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }


    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        //查询所有设备信息
        ListProductsRequest request = new ListProductsRequest();
        //设置条数
        request.setLimit(50);
        //发送请求
        ListProductsResponse response = aClient.listProducts(request);
        //判断是否成功
        if (response.getHttpStatusCode() != 200) {
            throw new RuntimeException("同步产品列表失败");
        }
        List<ProductSummary> products = response.getProducts();
        redisTemplate.opsForValue().set(Constants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(products));
    }

    /**
     * 获取所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //取出redis中数据
        String str = (String) redisTemplate.opsForValue().get(Constants.IOT_ALL_PRODUCT_LIST);
        if (StrUtil.isEmpty(str)) {
            return Collections.emptyList();
        }
        //转化为list集合
        return JSONUtil.toList(JSONUtil.parseArray(str), ProductVo.class);
    }

    /**
     * 注册设备
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //1.判断设备名称是否重复
        long count = this.count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()));
        if (count > 0) {
            throw new RuntimeException("设备名称重复");
        }
        //2.设备标识是否重复
        count = this.count(Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, deviceDto.getNodeId()));
        if (count > 0) {
            throw new RuntimeException("设备标识码重复");
        }
        //3.同一位置是否绑定了相同的产品
        count = this.count(Wrappers.<Device>lambdaQuery().
                eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(deviceDto.getPhysicalLocationType() != null, Device::getDeviceDescription, deviceDto.getProductName())
        );
        if (count > 0) {
            throw new RuntimeException("同一位置已绑定相同产品");
        }
        //4.注册设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.setProductId(deviceDto.getProductKey());
        body.setDeviceName(deviceDto.getDeviceName());
        body.setNodeId(deviceDto.getNodeId());
        //设置秘钥
        AuthInfo authInfo = new AuthInfo();
        String secret = UUID.randomUUID().toString().replace("-", "");
        authInfo.setSecret(secret);
        body.setAuthInfo(authInfo);
        request.setBody(body);
        AddDeviceResponse addDeviceResponse = aClient.addDevice(request);
        if (addDeviceResponse.getHttpStatusCode() != 201) {
            throw new RuntimeException("设备注册失败");
        }
        //5.保存到本地
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setSecret(secret);
        device.setIotId(addDeviceResponse.getDeviceId());
        //绑定位置
        device.setBindingLocation(String.valueOf(deviceDto.getBindingLocation()));
        this.save(device);
    }

    /**
     * 获取设备信息
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo getInfo(String iotId) {
        //本地查询
        Device one = this.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (ObjectUtil.isNull(one)) {
            throw new BaseException("设备不存在");
        }
        //获取设备信息
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse showDeviceResponse = aClient.showDevice(request);//http
        if (showDeviceResponse.getHttpStatusCode() != 200) {
            throw new BaseException("设备不存在");
        }
        //封装数据
        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(one, DeviceDetailVo.class);
        deviceDetailVo.setBindingLocation(Long.valueOf(one.getBindingLocation()));
        deviceDetailVo.setDeviceStatus(showDeviceResponse.getStatus());
        String time = showDeviceResponse.getActiveTime();
        if (StrUtil.isEmpty(time)) {
            deviceDetailVo.setActiveTime(null);
            return deviceDetailVo;
        }
        LocalDateTime activeTime = LocalDateTimeUtil.parse(time, DatePattern.UTC_MS_PATTERN);
        activeTime = DateTimeZoneConverter.utcToShanghai(activeTime);
        deviceDetailVo.setActiveTime(activeTime);

        return deviceDetailVo;
    }

    /**
     * 查询设备上报的数据
     *
     * @param iotId
     * @return
     */
    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {
        //1.查询设备最近上传的数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        //1.1根据设备的id进行查询
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = aClient.showDeviceShadow(request);
        //判断响应码
        if (response.getHttpStatusCode() != 200) {
            //响应码不是200 抛异常 说明该设备不存在
            throw new BaseException("设备不存在");
        }
        //否则的话证明查到了内容 获取数据 shadow设备影子数据结构体 存储的内容
        List<DeviceShadowData> shadow = response.getShadow();
        if (CollUtil.isEmpty(shadow)){
            //直接返回一个空的集合即可
            return Collections.emptyList();
        }
        //2封装数据
        //2.1 获取最近的List<DeviceShadowData>中的最新数据
        DeviceShadowData deviceShadowData = shadow.get(0);
        DeviceShadowProperties reported = deviceShadowData.getReported();
        //将以键值对存储的json数据转化为JSon对象
        JSONObject jsonObject = JSONUtil.parseObj(reported.getProperties());
        String eventTimeStr = reported.getEventTime();
        //转化时间
        // 把字符串转换为LocalDateTime
        LocalDateTime eventTimeLocalDateTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
        // 时区转换
        LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(eventTimeLocalDateTime);
        //对齐进行遍历
        List<Map<String, Object>> list = new ArrayList<>();

       /* jsonObject.forEach((key, value) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("functionId", key);
            map.put("value", value);
            map.put("eventTime", eventTime);
            list.add(map);
        });*/
        // k:属性标识，v:属性值
        jsonObject.forEach((k,v) -> {
            Map<String,Object> map = new HashMap<>();
            map.put("functionId", k);
            map.put("value", v);
            map.put("eventTime", eventTime);
            list.add(map);
        });
        return list;
    }

    /**
     * 修改设备信息
     *
     * @param dto
     */
    @Override
    public void updateDevice(DeviceDto dto) {

        //1.根据id查询设备信息
        Device device = this.getById(dto.getId());
        //2.如果设备名称发生改变 需要修改华为云的设备名称
        if (!(device.getDeviceName().equals(dto.getDeviceName()))){
            UpdateDeviceRequest request = new UpdateDeviceRequest();
            request.setDeviceId(device.getIotId());
            UpdateDevice body = new UpdateDevice();
            body.setDeviceName(dto.getDeviceName());
            request.setBody(body);
            UpdateDeviceResponse response = aClient.updateDevice(request);

            if (response.getHttpStatusCode() != 200){
                throw new BaseException("修改设备名称失败");
            }
        }
        //3.同一位置是否绑定了相同的产品
        long count = this.count(Wrappers.<Device>lambdaQuery().
                eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(dto.getPhysicalLocationType() != null, Device::getDeviceDescription, dto.getProductName())
        );
        if (count > 0){
            throw new BaseException("同一位置只能绑定一个产品");
        }
        //执行修改
        BeanUtil.copyProperties(dto,device);
        this.updateById( device);
    }

    /**
     * 删除设备
     *
     * @param iotId
     */
    @Override
    public void deleteDeviceByIotId(String iotId) {
        //查询设备信息
        boolean remove = this.remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (!remove){
            throw new BaseException("删除设备失败");
        }
        //删除华为云存储的设备信息
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);
        DeleteDeviceResponse response = aClient.deleteDevice(request);
        if (response.getHttpStatusCode()!=204) {
            throw new BaseException("IOT删除设备失败");
        }
    }

    /**&
     * 查询产品信息
     *
     * @param productKey
     * @return
     */
    @Override
    public List<ServiceCapability> queryProduct(String productKey) {
        if (StringUtils.isEmpty(productKey)) {
            throw new BaseException("产品Key不能为空");
        }
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response = aClient.showProduct(request);
        if (response.getHttpStatusCode() != 200) {
            return Collections.emptyList();
        }
        List<ServiceCapability> list = response.getServiceCapabilities();
        //如果list为空
        if (CollUtil.isEmpty(list)){
            return Collections.emptyList();
        }
        return  list;
    }
}
